package db

import (
	"database/sql"
	"financial/db/entity"
	"time"
	"github.com/satori/go.uuid"
	_ "github.com/go-sql-driver/mysql"
)

var EntityMap map[string]map[string]interface{} = make(map[string]map[string]interface{}, 0)

func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}

/**
添加用户
 */
func WriteUser(username, password, realName string) (bool, bool) {
	isAre := false
	isRegistered := false
	if len(password) != 0 && len(username) != 0 && len(realName) != 0 {
		if QueryUserData(username) != nil {
			isAre = true
			isRegistered = true
		}

		if !isAre {
			//打开数据库
			//"root:123456@/test?charset=utf8"
			//数据库用户 数据库密码 数据库 数据库编码
			db, err := sql.Open("mysql", "root:123456@/test?charset=utf8")
			defer db.Close()
			checkErr(err)
			_, err = db.Exec("INSERT userinfo SET username=?,password=?,created=?,real_name=?", username, password, time.Now().Unix(), realName)
			checkErr(err)
			rows, err := db.Query("SELECT * FROM userinfo WHERE  username=? AND password=?", username, password)
			checkErr(err)
			for rows.Next() {
				user := new(entity.UserInfo)
				_ = rows.Scan(&user.Uid, &user.Username, &user.Password, &user.Created, &user.RealName)
				var userMap map[string]interface{} = make(map[string]interface{}, 0)
				userMap[username] = *user
				EntityMap["userinfo"] = userMap
			}
			isAre = true
		}
	}
	return isAre, isRegistered
}

/**
添加用户费用
 */
func WriteUserCost(username string, use string, money float64, dormitoryUuid string) bool {
	isCorrectWrite := false
	if len(username) != 0 && money != 0.0 {

		//打开数据库
		//"root:123456@/test?charset=utf8"
		//数据库用户 数据库密码 数据库 数据库编码
		db, err := sql.Open("mysql", "root:123456@/test?charset=utf8")
		defer db.Close()
		checkErr(err)

		//10位的时间戳
		t := time.Now()
		createTime := t.Unix()

		//uuid
		uuid, _ := uuid.NewV4()
		_, err = db.Exec("INSERT usercost SET uuid=?,dormitory_uuid=?,username=?,use_info=?,money=?,create_time=?", uuid.String(), dormitoryUuid, username, use, money, createTime)
		if err != nil {
			checkErr(err)
		} else {
			isCorrectWrite = true
		}
	}

	return isCorrectWrite

}

/**
添加宿舍
 */
func WriteDormitoryInfo(dormitoryName string, owner string, members string, membersRealName string, memberNum int, address string) bool {
	isCorrectWrite := false
	if len(dormitoryName) != 0 && len(owner) != 0 && len(members) != 0 && len(membersRealName) != 0 && len(address) != 0 && memberNum != 0 {

		//打开数据库
		//"root:123456@/test?charset=utf8"
		//数据库用户 数据库密码 数据库 数据库编码
		db, err := sql.Open("mysql", "root:123456@/test?charset=utf8")
		defer db.Close()
		checkErr(err)

		//10位的时间戳
		t := time.Now()
		createTime := t.Unix()

		//uuid
		dormitoryUuid, _ := uuid.NewV4()
		_, err = db.Exec("INSERT dormitoryinfo SET dormitory_uuid=?,dormitory_name=?,owner=?,members=?,members_real_name=?,member_num=?,address=?,create_time=?", dormitoryUuid.String(), dormitoryName, owner, members, membersRealName, memberNum, address, createTime)
		if err != nil {
			checkErr(err)
		} else {
			isCorrectWrite = true
		}
	}

	return isCorrectWrite

}

/*
更新宿舍信息
 */
func UpdateDormitoryInfo(dormitoryUuid string, members string, membersRealName string, memberNum int, owner string) bool {
	isCorrectWrite := false
	if len(members) != 0 && len(membersRealName) != 0 {

		//打开数据库
		//"root:123456@/test?charset=utf8"
		//数据库用户 数据库密码 数据库 数据库编码
		db, err := sql.Open("mysql", "root:123456@/test?charset=utf8")
		defer db.Close()
		checkErr(err)

		_, err = db.Exec("UPDATE dormitoryinfo SET members=?,members_real_name=?,member_num=? WHERE dormitory_uuid=? AND owner=? ", members, membersRealName, memberNum, dormitoryUuid, owner)
		if err != nil {
			checkErr(err)
		} else {
			isCorrectWrite = true
		}
	}

	return isCorrectWrite

}

/**
查询用户费用数据
 */
func QueryUserCostData(username string, dormitoryUuid string, createTime int64, page int) []entity.UserCost {
	var userCostSlice []entity.UserCost = make([]entity.UserCost, 0)

	db, _ := sql.Open("mysql", "root:123456@/test?charset=utf8")
	defer db.Close()

	var rows *sql.Rows
	var err error
	if len(username) != 0 && createTime == 0 && len(dormitoryUuid) == 0 {
		num := (page - 1) * 10
		rows, err = db.Query("SELECT * FROM usercost WHERE username = ? order by create_time DESC limit ?,10", username, num)
	} else if len(username) == 0 && createTime != 0 && len(dormitoryUuid) == 0 {
		num := (page - 1) * 10
		rows, err = db.Query("SELECT * FROM usercost WHERE create_time >= ? order by create_time DESC limit ?,10", createTime, num)
	} else if len(username) != 0 && createTime != 0 && len(dormitoryUuid) == 0 {
		num := (page - 1) * 10
		rows, err = db.Query("SELECT * FROM usercost WHERE create_time >= ? AND username = ?  order by create_time DESC limit ?,10", createTime, username, num)
	} else if len(username) != 0 && createTime != 0 && len(dormitoryUuid) != 0 {
		num := (page - 1) * 10
		rows, err = db.Query("SELECT * FROM usercost WHERE create_time >= ? AND username = ? AND dormitory_uuid=? order by create_time DESC limit ?,10", createTime, username, dormitoryUuid, num)
	} else if len(username) == 0 && createTime == 0 && len(dormitoryUuid) != 0 {
		num := (page - 1) * 10
		rows, err = db.Query("SELECT * FROM usercost WHERE dormitory_uuid=? order by create_time DESC limit ?,10", dormitoryUuid, num)
	} else if len(username) == 0 && createTime != 0 && len(dormitoryUuid) != 0 {
		num := (page - 1) * 10
		rows, err = db.Query("SELECT * FROM usercost WHERE create_time >= ? AND dormitory_uuid=? order by create_time DESC limit ?,10", createTime, dormitoryUuid, num)
	} else {
		num := (page - 1) * 10
		rows, err = db.Query("SELECT * FROM usercost order by create_time DESC limit ?,10 ", num)
	}

	if err != nil {
		checkErr(err)
	} else {
		userCostSlice = entity.ReadUserCostData(rows)
	}
	return userCostSlice
}

/**
查询用户数据
 */
func QueryUserData(username string) *entity.UserInfo {
	var user *entity.UserInfo = nil

	if EntityMap["userinfo"][username] != nil {
		user = new(entity.UserInfo)
		*user = EntityMap["userinfo"][username].(entity.UserInfo)
	} else {
		db, err := sql.Open("mysql", "root:123456@/test?charset=utf8")
		defer db.Close()
		checkErr(err)
		rows, err := db.Query("SELECT * FROM userinfo WHERE username = ?", username)
		if err != nil {
			checkErr(err)
		} else {
			EntityMap["userinfo"] = entity.ReadUserData(rows)
			if EntityMap["userinfo"] [username] != nil {
				user = new(entity.UserInfo)
				*user = EntityMap["userinfo"][username].(entity.UserInfo)
			}
		}
	}
	return user
}

/**
查询该用户拥有的宿舍
 */

func QueryDormitoryInfoData(owner string) []entity.DormitoryInfo {
	var dormitoryInfoSlice []entity.DormitoryInfo = nil

	db, err := sql.Open("mysql", "root:123456@/test?charset=utf8")
	defer db.Close()
	checkErr(err)
	rows, err := db.Query("SELECT * FROM dormitoryinfo WHERE owner =?", owner)
	if err != nil {
		checkErr(err)
	} else {
		dormitoryInfoSlice = entity.ReadDormitoryInfoData(rows)
	}

	return dormitoryInfoSlice
}
